import 'package:yaml/yaml.dart';
import 'package:flutter/services.dart' show rootBundle;
import 'package:flutter/foundation.dart';
import 'dart:io';
import 'env_loader.dart';
import 'user_config.dart';

class ConfigLoader {
  static final ConfigLoader _instance = ConfigLoader._internal();
  factory ConfigLoader() => _instance;
  ConfigLoader._internal();

  late YamlMap _config;
  bool _isInitialized = false;
  final EnvLoader _envLoader = EnvLoader();
  final UserConfig _userConfig = UserConfig();

  /// 是否已初始化
  bool get isInitialized => _isInitialized;

  /// 初始化配置
  Future<void> init() async {
    if (_isInitialized) return;

    // 加载YAML配置文件
    final yamlString = await rootBundle.loadString('assets/config/config.yaml');
    _config = loadYaml(yamlString) as YamlMap;

    // 初始化用户配置
    await _userConfig.init();

    _isInitialized = true;
  }

  /// 获取当前环境
  String get environment {
    // 从配置文件获取环境设置
    String env = _getValue(['settings', 'environment'], 'development');

    // 如果是Android真机，自动切换到device环境
    if (!kIsWeb && Platform.isAndroid && !_isEmulator()) {
      env = 'device';
    }

    return env;
  }

  /// 检查是否在模拟器上运行
  bool _isEmulator() {
    if (!Platform.isAndroid) return false;

    try {
      // Android模拟器通常使用特定的设备型号
      final String androidModel = Platform.environment['ANDROID_MODEL'] ?? '';
      final String brand = Platform.environment['ANDROID_BRAND'] ?? '';
      final String device = Platform.environment['ANDROID_DEVICE'] ?? '';
      final String product = Platform.environment['ANDROID_PRODUCT'] ?? '';

      // 检查常见的模拟器标识
      return androidModel.toLowerCase().contains('sdk') ||
          brand.toLowerCase().contains('generic') ||
          device.toLowerCase().contains('generic') ||
          product.toLowerCase().contains('sdk') ||
          product.toLowerCase().contains('emulator');
    } catch (e) {
      print('检查模拟器状态时出错: $e');
      return false;
    }
  }

  /// 获取API配置
  Map<String, dynamic> get apiConfig {
    // 如果启用了用户配置且存在有效的用户API配置，则使用用户配置
    if (_userConfig.isEnabled && _userConfig.apiConfig != null) {
      return Map<String, dynamic>.from(_userConfig.apiConfig!);
    }

    final env = environment;
    final config = Map<String, dynamic>.from(_getValue(['api', env], {}));

    // 只在开发环境下处理localhost
    if (env == 'development' && !kIsWeb && Platform.isAndroid) {
      if (config['host'] == 'localhost') {
        config['host'] = '10.0.2.2'; // Android模拟器访问主机的特殊IP
      }
    }

    return config;
  }

  /// 获取全局设置
  Map<String, dynamic> get settings {
    return Map<String, dynamic>.from(_getValue(['settings'], {}));
  }

  /// 获取API基础URL
  String get apiBaseUrl {
    final config = apiConfig;
    return '${config['protocol']}://${config['host']}:${config['port']}${config['path_prefix']}';
  }

  /// 获取配置值
  dynamic _getValue(List<String> path, [dynamic defaultValue]) {
    dynamic current = _config;
    for (final key in path) {
      if (current is! Map) return defaultValue;
      if (!current.containsKey(key)) return defaultValue;
      current = current[key];
    }
    return current ?? defaultValue;
  }

  /// 获取超时设置（毫秒）
  int getTimeout(String service) {
    switch (service) {
      case 'api':
        return apiConfig['timeout'] ?? 15000;
      default:
        return 15000;
    }
  }

  /// 获取重试次数
  int getRetries(String service) {
    switch (service) {
      case 'api':
        return apiConfig['retries'] ?? 3;
      default:
        return 3;
    }
  }

  /// 获取缓存时间（秒）
  int get cacheDuration => settings['cache_duration'] ?? 3600;

  /// 获取最大上传大小（字节）
  int get maxUploadSize => settings['max_upload_size'] ?? 104857600;

  /// 是否启用调试日志
  bool get debugLogging => settings['debug_logging'] ?? false;

  /// 是否启用缓存
  bool get cacheEnabled => settings['cache_enabled'] ?? true;

  /// 获取用户配置管理器
  UserConfig get userConfig => _userConfig;
}
